using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using Giraffe.Client.Common;
using Giraffe.Core.Model;
using Giraffe.Core.Common;

namespace Giraffe.Client.MainWindowModule.Contacts
{
    public class ContactListViewModel: ViewModelBase
    {
        private readonly IUser _user;
        private ObservableCollection<ContactViewModel> _contacts;

        public ContactListViewModel( IUser user)
        {
            _user = user;
            _user.MessengerContactListChanged += OnMessengerContactListChanged;

        }

        private void OnMessengerContactListChanged()
        {
            UpdateContacts();
            RisePropertyChanged("Contacts");
        }

        public ObservableCollection<ContactViewModel> Contacts
        {
            get
            {
                if (_contacts == null)
                {
                    _contacts = new ObservableCollection<ContactViewModel>();
                    UpdateContacts();
                }
                return _contacts;
            }
        } 

        private void UpdateContacts()
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke((Action)UpdateContacts);
                return;
            }

            _contacts.Clear();
            
            var contactsList = new List<IContact>(_user.Contacts).ConvertAll(c => new ContactViewModel(c));
            foreach (ContactViewModel viewModel in contactsList)
            {
                _contacts.Add(viewModel);
            }
        }
   
    }
}